'use client';

import { useEffect, useState } from 'react';
import Link from 'next/link';
import { notFound, useParams } from 'next/navigation';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Plus, Receipt, Building2, ArrowLeft } from 'lucide-react';
import { formatMoney, formatDate, calculateProgress, getApiUrl } from '@/lib/utils';

const expenseTypeMap = {
  material: '材料费',
  labor: '人工费',
  equipment: '设备费',
  other: '其他费用'
} as const;

type ExpenseType = keyof typeof expenseTypeMap;

interface Expense {
  id: string;
  siteId: string;
  type: ExpenseType;
  amount: number;
  paymentDate: string;
  vendor: string | null;
  description: string | null;
}

interface Site {
  id: string;
  name: string;
  status: 'active' | 'completed' | 'paused';
  contractAmount: number;
  createdAt: string;
  expenses: Expense[];
}

function SiteDetails({ site }: { site: Site }) {
  // 计算各类支出总额
  const expenseStats = site.expenses.reduce((acc, expense) => {
    acc[expense.type] = (acc[expense.type] || 0) + expense.amount;
    return acc;
  }, {} as Record<string, number>);

  const totalExpenses = Object.values(expenseStats).reduce((a, b) => a + b, 0);
  const remainingBudget = site.contractAmount - totalExpenses;
  const progress = calculateProgress(totalExpenses, site.contractAmount);

  const statusMap = {
    active: '进行中',
    completed: '已完工',
    paused: '已暂停'
  };

  return (
    <div className="space-y-6">
      <div className="flex flex-col gap-4 md:flex-row md:items-start md:justify-between">
        <div>
          <h1 className="text-3xl font-bold tracking-tight">{site.name}</h1>
          <p className="text-muted-foreground">
            创建于 {formatDate(site.createdAt)}，状态：{statusMap[site.status]}
          </p>
        </div>
        <Button asChild>
          <Link href={`/expenses/new?siteId=${site.id}`}>
            <Plus className="mr-2 h-4 w-4" />
            记录支出
          </Link>
        </Button>
      </div>

      <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-4">
        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">合同金额</CardTitle>
            <Building2 className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{formatMoney(site.contractAmount)}</div>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">已支出金额</CardTitle>
            <Receipt className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{formatMoney(totalExpenses)}</div>
            <div className="mt-2 h-2 w-full rounded-full bg-secondary">
              <div
                className="h-2 rounded-full bg-primary"
                style={{ width: `${progress}%` }}
              />
            </div>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">剩余预算</CardTitle>
            <Building2 className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{formatMoney(remainingBudget)}</div>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">支出记录数</CardTitle>
            <Receipt className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{site.expenses.length}</div>
          </CardContent>
        </Card>
      </div>

      <div className="space-y-4">
        <h2 className="text-2xl font-bold tracking-tight">支出明细</h2>
        <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-3">
          {site.expenses.map((expense) => (
            <Link key={expense.id} href={`/expenses/${expense.id}`}>
              <Card className="hover:bg-muted/50 transition-colors">
                <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
                  <CardTitle className="text-sm font-medium">
                    {expenseTypeMap[expense.type]}
                  </CardTitle>
                  <Receipt className="h-4 w-4 text-muted-foreground" />
                </CardHeader>
                <CardContent>
                  <div className="text-2xl font-bold">{formatMoney(expense.amount)}</div>
                  <div className="text-xs text-muted-foreground space-y-1">
                    <div>支付时间: {formatDate(expense.paymentDate)}</div>
                    {expense.vendor && <div>供应商: {expense.vendor}</div>}
                    {expense.description && (
                      <div className="line-clamp-2">备注: {expense.description}</div>
                    )}
                  </div>
                </CardContent>
              </Card>
            </Link>
          ))}
        </div>
      </div>
    </div>
  );
}

export default function SitePage() {
  const params = useParams();
  const id = params.id as string;
  const [site, setSite] = useState<Site | null>(null);
  const [isLoading, setIsLoading] = useState(true);

  useEffect(() => {
    async function loadSite() {
      try {
        const response = await fetch(getApiUrl(`sites/${id}`));
        if (!response.ok) {
          if (response.status === 404) {
            notFound();
          }
          throw new Error('加载工地详情失败');
        }
        const data = await response.json();
        setSite(data);
      } catch (error) {
        console.error('加载工地详情失败:', error);
      } finally {
        setIsLoading(false);
      }
    }
    loadSite();
  }, [id]);

  if (isLoading) {
    return (
      <main className="container mx-auto p-4 space-y-4">
        <Button variant="ghost" asChild className="mb-4">
          <Link href="/sites">
            <ArrowLeft className="mr-2 h-4 w-4" />
            返回工地列表
          </Link>
        </Button>
        <div>加载中...</div>
      </main>
    );
  }

  if (!site) {
    return (
      <main className="container mx-auto p-4 space-y-4">
        <Button variant="ghost" asChild className="mb-4">
          <Link href="/sites">
            <ArrowLeft className="mr-2 h-4 w-4" />
            返回工地列表
          </Link>
        </Button>
        <div>工地不存在</div>
      </main>
    );
  }

  return (
    <main className="container mx-auto p-4 space-y-4">
      <Button variant="ghost" asChild className="mb-4">
        <Link href="/sites">
          <ArrowLeft className="mr-2 h-4 w-4" />
          返回工地列表
        </Link>
      </Button>

      <SiteDetails site={site} />
    </main>
  );
} 